package com.ruoyi.business.service.koc.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.*;
import com.ruoyi.business.domain.bo.InRewardResult;
import com.ruoyi.business.domain.bo.OutRewardResult;
import com.ruoyi.business.domain.dto.admin.koc.TaskCheckDTO;
import com.ruoyi.business.domain.dto.admin.koc.TbUserKocTaskInfoPageDTO;
import com.ruoyi.business.domain.dto.api.koc.SubmitKocTaskDTO;
import com.ruoyi.business.domain.dto.api.koc.UpdateKocTaskDetailDTO;
import com.ruoyi.business.domain.koc.*;
import com.ruoyi.business.domain.vo.*;
import com.ruoyi.business.mapper.koc.TbUserKocTaskInfoMapper;
import com.ruoyi.business.service.koc.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.business.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TbUserKocTaskInfoServiceImpl extends ServiceImpl<TbUserKocTaskInfoMapper, TbUserKocTaskInfo> implements ITbUserKocTaskInfoService {

    @Resource
    private ITbUserService tbUserService;

    @Resource
    private ITbKocLevelService tbKocLevelService;

    @Resource
    private ITbKocTaskTypeService tbKocTaskTypeService;

    @Resource
    private ITbKocTaskService tbKocTaskService;

    @Resource
    private ITbUserKocTaskInfoDetailService tbUserKocTaskInfoDetailService;

    @Resource
    @Lazy
    private ITbUserKocPointsLogService tbUserKocPointsLogService;

    @Resource
    @Lazy
    private ITbUserKocProductLogService tbUserKocProductLogService;

    @Resource
    private ITbProductExchangeCouponService productExchangeCouponService;


    private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

    @Override
    public TableDataInfo<TbUserKocTaskGroupInfoVO> selectPageList(TbUserKocTaskInfoPageDTO dto, PageQuery pageQuery) {
        Page<TbUserKocTaskGroupInfoVO> page = pageQuery.build();
        IPage<TbUserKocTaskGroupInfoVO> pageRes = baseMapper.selectPageList(page, dto);
        return TableDataInfo.build(pageRes);
    }


    @Override
    public TbUserKocTaskInfoAllVO selectUserTaskAllInfo(Long userId, Long taskId, String kocDate, Integer checkStatus) {
        TbKocTask tbKocTask = tbKocTaskService.getById(taskId);
        TbUser tbUser = tbUserService.getById(userId);
        LambdaQueryWrapper<TbUserKocTaskInfo> tbUserKocTaskInfoLambdaQueryWrapper = Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
            .eq(TbUserKocTaskInfo::getUserId, userId)
            .eq(TbUserKocTaskInfo::getKocTaskId, taskId)
            .eq(TbUserKocTaskInfo::getKocDate, kocDate)
            .orderByAsc(TbUserKocTaskInfo::getCreateTime);
        if (ObjectUtils.isNotEmpty(checkStatus)) {
            if (checkStatus.equals(TaskCheckStatusEnum.CHECKED.getStatus())) {
                List<Integer> statusList = new ArrayList<>();
                statusList.add(TaskCheckStatusEnum.CHECK_PASS.getStatus());
                statusList.add(TaskCheckStatusEnum.CHECK_PASS_NOT.getStatus());
                tbUserKocTaskInfoLambdaQueryWrapper.in(TbUserKocTaskInfo::getCheckStatus, statusList);
            } else {
                tbUserKocTaskInfoLambdaQueryWrapper.eq(TbUserKocTaskInfo::getCheckStatus, checkStatus);
            }
        }
        List<TbUserKocTaskInfo> tbUserKocTaskInfoList = this.list(tbUserKocTaskInfoLambdaQueryWrapper);
        List<Long> tbUserKocTaskInfoIds = tbUserKocTaskInfoList.stream().map(TbUserKocTaskInfo::getId).collect(Collectors.toList());
        List<TbUserKocTaskInfoDetail> tbUserKocTaskInfoDetailList = tbUserKocTaskInfoDetailService.list(Wrappers.lambdaQuery(TbUserKocTaskInfoDetail.class)
            .in(TbUserKocTaskInfoDetail::getKocTaskInfoId, tbUserKocTaskInfoIds)
            .orderByDesc(TbUserKocTaskInfoDetail::getCreateTime));
        Map<Long, List<TbUserKocTaskInfoDetail>> detailMap = tbUserKocTaskInfoDetailList.stream().collect(Collectors.groupingBy(TbUserKocTaskInfoDetail::getKocTaskInfoId));
        List<TbUserKocTaskInfoUserDetailVO> tbUserKocTaskInfoUserDetailVOList = new ArrayList<>();
        tbUserKocTaskInfoList.forEach(taskInfo -> {
            TbUserKocTaskInfoUserDetailVO bean = BeanUtil.toBean(taskInfo, TbUserKocTaskInfoUserDetailVO.class);
            bean.setTbUserKocTaskInfoDetails(BeanUtil.copyToList(detailMap.get(bean.getId()), TbUserKocTaskInfoDetailVO.class));
            tbUserKocTaskInfoUserDetailVOList.add(bean);
        });
        return TbUserKocTaskInfoAllVO.builder().tbUser(tbUser).tbKocTask(tbKocTask).tbUserKocTaskInfos(tbUserKocTaskInfoUserDetailVOList).build();
    }

    @Override
    public TableDataInfo<TbUserKocTaskInfo> selectMyTaskInfo(Long userId, Long kocTaskTypeId, Long kocTaskId, String kocDate, PageQuery pageQuery) {
        LambdaQueryWrapper<TbUserKocTaskInfo> tbUserKocTaskInfoLambdaQueryWrapper = Wrappers.lambdaQuery(TbUserKocTaskInfo.class);
        tbUserKocTaskInfoLambdaQueryWrapper.eq(TbUserKocTaskInfo::getUserId, userId);
        // kocTaskTypeId
        tbUserKocTaskInfoLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(kocTaskTypeId), TbUserKocTaskInfo::getKocTaskTypeId, kocTaskTypeId);
        // kocTaskId
        tbUserKocTaskInfoLambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(kocTaskId), TbUserKocTaskInfo::getKocTaskId, kocTaskId);
        // kocDate
        tbUserKocTaskInfoLambdaQueryWrapper.eq(StringUtils.isNotEmpty(kocDate), TbUserKocTaskInfo::getKocDate, kocDate);
        tbUserKocTaskInfoLambdaQueryWrapper.orderByDesc(TbUserKocTaskInfo::getCreateTime);
        Page<TbUserKocTaskInfo> page = this.page(pageQuery.build(), tbUserKocTaskInfoLambdaQueryWrapper);
        return TableDataInfo.build(page);
    }

    @Override
    public TbUserKocTaskInfoAppVO selectMyTaskInfoDetail(Long userId, Long kocTaskInfoId) {
        TbUserKocTaskInfo tbUserKocTaskInfo = this.getById(kocTaskInfoId);
        TbUserKocTaskInfoAppVO tbUserKocTaskInfoAppVO = BeanUtil.toBean(tbUserKocTaskInfo, TbUserKocTaskInfoAppVO.class);
        List<TbUserKocTaskInfoDetail> list = tbUserKocTaskInfoDetailService.list(Wrappers.lambdaQuery(TbUserKocTaskInfoDetail.class).eq(TbUserKocTaskInfoDetail::getUserId, userId).eq(TbUserKocTaskInfoDetail::getKocTaskInfoId, kocTaskInfoId).orderByAsc(TbUserKocTaskInfoDetail::getCreateTime));
        List<TbUserKocTaskInfoDetailAppVO> tbUserKocTaskInfoDetailAppVOS = BeanUtil.copyToList(list, TbUserKocTaskInfoDetailAppVO.class);
        tbUserKocTaskInfoAppVO.setTaskInfoDetailInfo(tbUserKocTaskInfoDetailAppVOS);
        return tbUserKocTaskInfoAppVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean userSubmitKocTask(Long userId, SubmitKocTaskDTO dto) {
        TbUser tbUser = tbUserService.getById(userId);
        if (Objects.equals(tbUser.getIsKoc(), Constants.FALSE_0)) {
            throw new ServiceException("请先申请成为koc用户");
        }
        TbKocTaskType tbKocTaskType = tbKocTaskTypeService.getById(dto.getKocTaskTypeId());
        if (ObjectUtils.isEmpty(tbKocTaskType)) {
            throw new ServiceException("taskTypeId 参数有误");
        }
        TbKocTask tbKocTask = tbKocTaskService.getById(dto.getKocTaskId());
        if (ObjectUtils.isEmpty(tbKocTask)) {
            throw new ServiceException("taskId 参数有误");
        }
        TbKocLevel tbKocLevel = tbKocLevelService.getById(tbUser.getKocLevelId());
        // 每月的频率限制
        if (StringUtils.equals(KocTaskEnum.NBQFY.getCode(), tbKocTask.getCode())) {
            // 查询当期用户的任务提交数量
            Long l = this.baseMapper.selectCount(Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                .eq(TbUserKocTaskInfo::getUserId, userId)
                .eq(TbUserKocTaskInfo::getKocTaskId, dto.getKocTaskId())
                .eq(TbUserKocTaskInfo::getKocDate, formatter.format(new Date()))
            );
            if (l >= tbKocTask.getMaxClaimable()) {
                throw new ServiceException("任务超出可做频率配置,如未审核可修改任务详情");
            }

        }
        // koc用户提交任务信息
        TbUserKocTaskInfo tbUserKocTaskInfo = new TbUserKocTaskInfo();
        long taskId = IdWorker.getId();
        tbUserKocTaskInfo.setId(taskId);
        tbUserKocTaskInfo.setKocTaskTypeId(tbKocTaskType.getId());
        tbUserKocTaskInfo.setKocTaskTypeCode(StringUtils.isNotEmpty(tbKocTaskType.getCode()) ? tbKocTaskType.getCode() : org.apache.commons.lang3.StringUtils.EMPTY);
        tbUserKocTaskInfo.setKocTaskTypeName(tbKocTaskType.getName());
        tbUserKocTaskInfo.setKocTaskId(tbKocTask.getId());
        tbUserKocTaskInfo.setKocTaskName(tbKocTask.getName());
        tbUserKocTaskInfo.setUserId(tbUser.getId());
        tbUserKocTaskInfo.setUserPhone(tbUser.getMobile());
        tbUserKocTaskInfo.setUserRealName(StringUtils.isNotEmpty(tbUser.getRealName()) ? tbUser.getRealName() : org.apache.commons.lang3.StringUtils.EMPTY);
        tbUserKocTaskInfo.setUserNickname(StringUtils.isNotEmpty(tbUser.getNickname()) ? tbUser.getNickname() : org.apache.commons.lang3.StringUtils.EMPTY);
        tbUserKocTaskInfo.setUserKocLevelName(tbKocLevel.getName());
        tbUserKocTaskInfo.setUserKocLevelId(tbKocLevel.getId());
        tbUserKocTaskInfo.setKocDate(formatter.format(new Date()));
        tbUserKocTaskInfo.setCheckStatus(TaskCheckStatusEnum.ORIGINAL.getStatus());
        tbUserKocTaskInfo.setRemarks(StringUtils.isNotEmpty(dto.getRemarks()) ? dto.getRemarks() : org.apache.commons.lang3.StringUtils.EMPTY);
        tbUserKocTaskInfo.setCreateTime(new Date());
        this.save(tbUserKocTaskInfo);
        List<TbUserKocTaskInfoDetail> taskDetail = new ArrayList<>();
        dto.getDetails().forEach(detail -> {
            TbUserKocTaskInfoDetail tbUserKocTaskInfoDetail = new TbUserKocTaskInfoDetail();
            tbUserKocTaskInfoDetail.setId(IdWorker.getId());
            tbUserKocTaskInfoDetail.setUserId(tbUser.getId());
            tbUserKocTaskInfoDetail.setKocTaskInfoId(taskId);
            tbUserKocTaskInfoDetail.setDefinitionName(StringUtils.isEmpty(detail.getDefinitionName()) ? org.apache.commons.lang3.StringUtils.EMPTY : detail.getDefinitionName());
            tbUserKocTaskInfoDetail.setMultType(detail.getMultType());
            tbUserKocTaskInfoDetail.setPicUrl(CollectionUtils.isNotEmpty(detail.getPicUrl()) ? String.join(",", detail.getPicUrl()) : "");
            tbUserKocTaskInfoDetail.setVideoUrl(CollectionUtils.isNotEmpty(detail.getVideoUrl()) ? String.join(",", detail.getVideoUrl()) : "");
            tbUserKocTaskInfoDetail.setLinkUrl(CollectionUtils.isNotEmpty(detail.getLinkUrl()) ? String.join(",", detail.getLinkUrl()) : "");
            tbUserKocTaskInfoDetail.setRemarks(detail.getRemarks());
            tbUserKocTaskInfoDetail.setCreateTime(new Date());
            taskDetail.add(tbUserKocTaskInfoDetail);
        });
        return tbUserKocTaskInfoDetailService.saveBatch(taskDetail);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modifyKocTaskDetail(Long userId, UpdateKocTaskDetailDTO dto) {
        TbUser tbUser = tbUserService.getById(userId);
        if (tbUser.getIsKoc() == 0) {
            throw new ServiceException("请先申请成为koc用户");
        }
        TbUserKocTaskInfo tbUserKocTaskInfo = this.getById(dto.getUserKocTaskInfoId());
        if (!Objects.equals(tbUserKocTaskInfo.getCheckStatus(), TaskCheckStatusEnum.ORIGINAL.getStatus())) {
            throw new ServiceException("任务已审核状态不允许修改");
        }
        // 本期次不允许修改上期次
        if (!StringUtils.equals(tbUserKocTaskInfo.getKocDate(), formatter.format(new Date()))) {
            throw new ServiceException("历史期次任务不允许修改");
        }
        if (!Objects.equals(tbUserKocTaskInfo.getUserId(), userId)) {
            throw new ServiceException("参数有误");
        }
        // 先移除 后新增
        tbUserKocTaskInfoDetailService.remove(Wrappers.lambdaQuery(TbUserKocTaskInfoDetail.class).eq(TbUserKocTaskInfoDetail::getKocTaskInfoId, dto.getUserKocTaskInfoId()));
        List<TbUserKocTaskInfoDetail> taskDetail = new ArrayList<>();
        dto.getDetails().forEach(detail -> {
            TbUserKocTaskInfoDetail tbUserKocTaskInfoDetail = new TbUserKocTaskInfoDetail();
            tbUserKocTaskInfoDetail.setId(IdWorker.getId());
            tbUserKocTaskInfoDetail.setUserId(tbUser.getId());
            tbUserKocTaskInfoDetail.setKocTaskInfoId(dto.getUserKocTaskInfoId());
            tbUserKocTaskInfoDetail.setDefinitionName(StringUtils.isEmpty(detail.getDefinitionName()) ? org.apache.commons.lang3.StringUtils.EMPTY : detail.getDefinitionName());
            tbUserKocTaskInfoDetail.setMultType(detail.getMultType());
            tbUserKocTaskInfoDetail.setPicUrl(CollectionUtils.isNotEmpty(detail.getPicUrl()) ? detail.getPicUrl().stream().collect(Collectors.joining(",")) : "");
            tbUserKocTaskInfoDetail.setVideoUrl(CollectionUtils.isNotEmpty(detail.getVideoUrl()) ? detail.getVideoUrl().stream().collect(Collectors.joining(",")) : "");
            tbUserKocTaskInfoDetail.setLinkUrl(CollectionUtils.isNotEmpty(detail.getLinkUrl()) ? detail.getLinkUrl().stream().collect(Collectors.joining(",")) : "");
            tbUserKocTaskInfoDetail.setRemarks(detail.getRemarks());
            tbUserKocTaskInfoDetail.setCreateTime(new Date());
            taskDetail.add(tbUserKocTaskInfoDetail);
        });
        return tbUserKocTaskInfoDetailService.saveBatch(taskDetail);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delKocTaskInfo(Long userId, Long kocTaskInfoId) {
        TbUserKocTaskInfo tbUserKocTaskInfo = this.getById(kocTaskInfoId);
        if (!tbUserKocTaskInfo.getUserId().equals(userId)) {
            throw new ServiceException("数据异常");
        }
        if (ObjectUtils.isEmpty(tbUserKocTaskInfo)) {
            throw new ServiceException("数据异常");
        }
        if (!tbUserKocTaskInfo.getCheckStatus().equals(TaskCheckStatusEnum.ORIGINAL.getStatus())) {
            throw new ServiceException("任务已审核不允许删除");
        }
        this.removeById(kocTaskInfoId);
        return tbUserKocTaskInfoDetailService.remove(Wrappers.lambdaQuery(TbUserKocTaskInfoDetail.class).eq(TbUserKocTaskInfoDetail::getKocTaskInfoId, kocTaskInfoId));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean taskCheck(TaskCheckDTO dto) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        TbUserKocTaskInfo tbUserKocTaskInfo = this.getById(dto.getKocTaskInfoId());
        if (!Objects.equals(tbUserKocTaskInfo.getCheckStatus(), TaskCheckStatusEnum.ORIGINAL.getStatus())) {
            throw new ServiceException("请勿重复审核");
        }
        TbKocTask tbKocTask = tbKocTaskService.getById(tbUserKocTaskInfo.getKocTaskId());
        // 1:固定积分 2:拉新规则 3:品质积分 4:外群规则 5:内群规则 6:素材种类 7:小红书奖励规则 手动输入积分 与 产品数量
        Integer rewardRuleType = tbKocTask.getRewardRuleType();
        long checkBusinessId = IdWorker.getId();
        Gson gson = new Gson();
        String jsonString = gson.toJson(dto);
        tbUserKocTaskInfo.setCheckUser(loginUser.getUsername());
        tbUserKocTaskInfo.setCheckBusinessId(checkBusinessId);
        tbUserKocTaskInfo.setCheckRemarks(dto.getCheckRemarks());
        tbUserKocTaskInfo.setCheckTime(new Date());
        tbUserKocTaskInfo.setCheckParam(jsonString);
        // 审核通过
        if (Objects.equals(dto.getCheck(), TaskCheckStatusEnum.CHECK_PASS.getStatus())) {
            // 增加用户积分
            TbUser tbUser = tbUserService.selectByIdForUpdate(tbUserKocTaskInfo.getUserId());
            tbUserKocTaskInfo.setCheckStatus(TaskCheckStatusEnum.CHECK_PASS.getStatus());
            JsonObject jsonObject = null;
            if (Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.XHS_TYPE_REWARD.getStatus())
                || Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.OUT_CHAT_GROUP_REWARD.getStatus())
                || Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.MATERIAL_TYPE_REWARD.getStatus())
            ) {
                jsonObject = new JsonObject();
            } else {
                jsonObject = JsonParser.parseString(tbKocTask.getRewardSetting()).getAsJsonObject();
            }
            // 审核通过
            switch (TaskRewardRuleTypeEnum.getEnumByType(rewardRuleType)) {
                case FIXED_REWARD:
                    JsonObject fixedRewardSetting = jsonObject.getAsJsonObject("setting");
                    // 固定积分规则
                    int fixedReward = fixedRewardSetting.get("fixedReward").getAsInt();
                    tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                    tbUserKocTaskInfo.setRewardPoints(fixedReward);
                    tbUserKocTaskInfo.setRewardProduct(0);
                    this.updateById(tbUserKocTaskInfo);
                    // 插入积分流水
                    insertPointsLog(tbUserKocTaskInfo, tbUser, fixedReward);
                    tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + fixedReward).set(TbUser::getFreePoints, tbUser.getFreePoints() + fixedReward).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    break;
                case INVITATION_REWARD:
                    JsonObject invitationSetting = jsonObject.getAsJsonObject("setting");
                    // 拉新积分规则
                    JsonArray potential = invitationSetting.getAsJsonArray("potential");
                    JsonArray official = invitationSetting.getAsJsonArray("official");
                    int potentialReward = calculateReward(potential, dto.getPotentialNum());
                    // 非潜在用户
                    int officialReward = calculateReward(official, dto.getOfficialNum());
                    // 总分
                    int totalReward = potentialReward + officialReward;
                    tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                    tbUserKocTaskInfo.setRewardPoints(totalReward);
                    tbUserKocTaskInfo.setRewardProduct(0);
                    this.updateById(tbUserKocTaskInfo);
                    // 插入积分流水
                    insertPointsLog(tbUserKocTaskInfo, tbUser, totalReward);
                    tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + totalReward).set(TbUser::getFreePoints, tbUser.getFreePoints() + totalReward).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    break;
                case QUALITY_REWARD:
                    //品质积分规则
                    JsonArray qualityRewardSetting = jsonObject.getAsJsonArray("setting");
                    JsonObject rewardByLevel = findRewardByLevel(qualityRewardSetting, dto.getLevel());
                    int baseReward = rewardByLevel.get("baseReward").getAsInt();
                    int productCount = rewardByLevel.get("productCount").getAsInt();
                    if (baseReward > 0 && productCount == 0) {
                        // 只有积分
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(baseReward);
                        tbUserKocTaskInfo.setRewardProduct(0);
                        this.updateById(tbUserKocTaskInfo);
                        // 插入积分流水
                        insertPointsLog(tbUserKocTaskInfo, tbUser, baseReward);
                        tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + baseReward).set(TbUser::getFreePoints, tbUser.getFreePoints() + baseReward).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    }
                    if (baseReward == 0 && productCount > 0) {
                        //只有产品
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(0);
                        tbUserKocTaskInfo.setRewardProduct(productCount);
                        this.updateById(tbUserKocTaskInfo);
                        insertProductLog(tbUserKocTaskInfo, tbUser, productCount);
                    }
                    break;
                case OUT_CHAT_GROUP_REWARD:
                    // 外部群积分规则
                    OutRewardResult outRewardResult = calculateOutReward(jsonObject, dto.getOutGroupChatTimes(), dto.getOutGroupChatNum());
                    if (outRewardResult.getTotalPoints() > 0 && outRewardResult.isGetsProduct()) {
                        // 有积分 有产品
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.PRODUCT_POINTS.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(outRewardResult.getTotalPoints());
                        tbUserKocTaskInfo.setRewardProduct(1);
                        this.updateById(tbUserKocTaskInfo);
                        // 插入积分流水
                        insertPointsLog(tbUserKocTaskInfo, tbUser, outRewardResult.getTotalPoints());
                        // 插入产品流水
                        insertProductLog(tbUserKocTaskInfo, tbUser, 1);
                        // 修改积分
                        tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + outRewardResult.getTotalPoints()).set(TbUser::getFreePoints, tbUser.getFreePoints() + outRewardResult.getTotalPoints()).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    }
                    if (outRewardResult.getTotalPoints() == 0 && outRewardResult.isGetsProduct()) {
                        // 只有产品
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        tbUserKocTaskInfo.setRewardProduct(1);
                        tbUserKocTaskInfo.setRewardPoints(0);
                        this.updateById(tbUserKocTaskInfo);
                        insertProductLog(tbUserKocTaskInfo, tbUser, 1);
                    }
                    if (outRewardResult.getTotalPoints() > 0 && !outRewardResult.isGetsProduct()) {
                        // 只有积分
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(outRewardResult.getTotalPoints());
                        tbUserKocTaskInfo.setRewardProduct(0);
                        this.updateById(tbUserKocTaskInfo);
                        // 插入积分流水
                        insertPointsLog(tbUserKocTaskInfo, tbUser, outRewardResult.getTotalPoints());
                        tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + outRewardResult.getTotalPoints()).set(TbUser::getFreePoints, tbUser.getFreePoints() + outRewardResult.getTotalPoints()).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    }
                    break;
                case XHS_TYPE_REWARD:
                case IN_CHAT_GROUP_REWARD:
                case MATERIAL_TYPE_REWARD:
                    if (dto.getPoints() > 0 && dto.getProduct() > 0) {
                        // 有产品 有积分
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.PRODUCT_POINTS.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(dto.getPoints());
                        tbUserKocTaskInfo.setRewardProduct(dto.getProduct());
                        this.updateById(tbUserKocTaskInfo);
                        // 插入积分流水
                        insertPointsLog(tbUserKocTaskInfo, tbUser, dto.getPoints());
                        // 插入产品流水
                        insertProductLog(tbUserKocTaskInfo, tbUser, dto.getProduct());
                        tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + dto.getPoints()).set(TbUser::getFreePoints, tbUser.getFreePoints() + dto.getPoints()).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    }
                    if (dto.getPoints() > 0 && dto.getProduct() == 0) {
                        // 只有积分
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(dto.getPoints());
                        tbUserKocTaskInfo.setRewardProduct(0);
                        this.updateById(tbUserKocTaskInfo);
                        // 插入积分流水
                        insertPointsLog(tbUserKocTaskInfo, tbUser, dto.getPoints());
                        tbUserService.update(Wrappers.lambdaUpdate(TbUser.class).set(TbUser::getTotalPoints, tbUser.getTotalPoints() + dto.getPoints()).set(TbUser::getFreePoints, tbUser.getFreePoints() + dto.getPoints()).eq(TbUser::getId, tbUserKocTaskInfo.getUserId()));
                    }
                    if (dto.getPoints() == 0 && dto.getProduct() > 0) {
                        // 只有产品
                        tbUserKocTaskInfo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        tbUserKocTaskInfo.setRewardPoints(0);
                        tbUserKocTaskInfo.setRewardProduct(dto.getProduct());
                        this.updateById(tbUserKocTaskInfo);
                        insertProductLog(tbUserKocTaskInfo, tbUser, dto.getProduct());
                    }
                    break;
                default:
                    throw new ServiceException("奖励类型不存在");
            }
            // 校验任务是否达成
            if (ObjectUtil.equals(tbKocTask.getTaskTypeId(), KocTaskTypeEnum.GHHD.getKocTaskTypeId())) {
                // 查询是否已经发放过奖励
                TbUserKocProductLog tbUserKocProductLog = tbUserKocProductLogService.getBaseMapper().selectOne(
                    Wrappers.lambdaQuery(TbUserKocProductLog.class)
                        .eq(TbUserKocProductLog::getUserId, tbUserKocTaskInfo.getUserId())
                        .eq(TbUserKocProductLog::getKocDate, tbUserKocTaskInfo.getKocDate())
                        .eq(TbUserKocProductLog::getKocTaskTypeId, KocTaskTypeEnum.GHHD.getKocTaskTypeId())
                        .eq(TbUserKocProductLog::getSourceType, UserProductSourceTypeEnum.KOC_TASK_TYPE_ALL_DONE.getType())
                        .last(Constants.MYBATIS_PLUSH_LIMIT_ONE)
                );
                if (ObjectUtil.isEmpty(tbUserKocProductLog)) {
                    // 判断奖励是否发放
                    List<TbUserKocTaskInfo> userKocTaskInfos = this.list(Wrappers.lambdaQuery(TbUserKocTaskInfo.class)
                        .eq(TbUserKocTaskInfo::getCheckStatus, TaskCheckStatusEnum.CHECK_PASS.getStatus())
                        .eq(TbUserKocTaskInfo::getKocTaskTypeId, KocTaskTypeEnum.GHHD.getKocTaskTypeId())
                        .eq(TbUserKocTaskInfo::getUserId, tbUserKocTaskInfo.getUserId())
                        .eq(TbUserKocTaskInfo::getKocDate, tbUserKocTaskInfo.getKocDate()));
                    // 提取已通过的任务ID集合
                    Set<Long> passedTaskIds = userKocTaskInfos.stream()
                        .map(TbUserKocTaskInfo::getKocTaskId)
                        .collect(Collectors.toSet());

                    // 定义需要完成的四种任务ID
                    Set<Long> requiredTaskIds = new HashSet<>(Arrays.asList(
                        KocTaskEnum.WXSPH.getKocTaskId(),
                        KocTaskEnum.GZH.getKocTaskId(),
                        KocTaskEnum.XHS.getKocTaskId(),
                        KocTaskEnum.WB.getKocTaskId()
                    ));
                    // 判断是否包含所有四种任务
                    if (passedTaskIds.containsAll(requiredTaskIds)) {
                        long productLogId = IdWorker.getId();
                        // 创建产品发放记录
                        TbUserKocProductLog productLog = new TbUserKocProductLog();
                        productLog.setId(productLogId);
                        productLog.setUserId(tbUser.getId());
                        productLog.setKocTaskTypeId(KocTaskTypeEnum.GHHD.getKocTaskTypeId());
                        productLog.setKocTaskTypeName(KocTaskTypeEnum.GHHD.getName());
                        productLog.setUserPhone(tbUser.getMobile());
                        productLog.setUserRealName(tbUser.getRealName());
                        productLog.setUserKocLevelId(tbUser.getKocLevelId());
                        productLog.setKocDate(tbUserKocTaskInfo.getKocDate());
                        productLog.setSourceType(UserProductSourceTypeEnum.KOC_TASK_TYPE_ALL_DONE.getType());
                        productLog.setKocProductNum(1);
                        productLog.setSourceId(null);
                        productLog.setStatus(0);
                        productLog.setRemarks(UserProductSourceTypeEnum.KOC_TASK_TYPE_ALL_DONE.getDesc());
                        productLog.setCreateTime(new Date());
                        // 创建兑换券
                        TbProductExchangeCoupon coupon = new TbProductExchangeCoupon();
                        coupon.setId(IdWorker.getId());
                        coupon.setCouponCode(String.valueOf(IdWorker.getId()));
                        coupon.setCouponName(CouponTypeEnum.PHYSICAL.getDesc());
                        coupon.setCouponType(CouponTypeEnum.PHYSICAL.getCode());
                        coupon.setStatus(CouponStatusEnum.UNUSED.getCode());
                        coupon.setUserId(tbUser.getId());
                        coupon.setApplicableScope(ApplicableScopeEnum.UNIVERSAL.getCode());
                        coupon.setSourceId(productLogId);
                        coupon.setSourceType(CouponSourceTypeEnum.KOC_TASK.getType());
                        coupon.setCreateTime(new Date());
                        tbUserKocProductLogService.save(productLog);
                        productExchangeCouponService.save(coupon);
                    }

                }

            }
        }
        // 审核不通过
        if (Objects.equals(dto.getCheck(), TaskCheckStatusEnum.CHECK_PASS_NOT.getStatus())) {
            tbUserKocTaskInfo.setCheckStatus(TaskCheckStatusEnum.CHECK_PASS_NOT.getStatus());
            this.updateById(tbUserKocTaskInfo);
        }
        return true;
    }

    @Override
    public PreTaskCheckVO preTaskCheck(TaskCheckDTO dto) {
        TbUserKocTaskInfo tbUserKocTaskInfo = this.getById(dto.getKocTaskInfoId());
        TbKocTask tbKocTask = tbKocTaskService.getById(tbUserKocTaskInfo.getKocTaskId());
        // 1:固定积分 2:拉新规则 3:品质积分 4:外群规则 5:内群规则 6:素材种类
        Integer rewardRuleType = tbKocTask.getRewardRuleType();
        // 审核通过
        if (Objects.equals(dto.getCheck(), TaskCheckStatusEnum.CHECK_PASS.getStatus())) {
            PreTaskCheckVO resVo = PreTaskCheckVO.builder().build();
            tbUserKocTaskInfo.setCheckStatus(TaskCheckStatusEnum.CHECK_PASS.getStatus());
            JsonObject jsonObject = null;
            if (Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.XHS_TYPE_REWARD.getStatus())
                || Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.IN_CHAT_GROUP_REWARD.getStatus())
                || Objects.equals(rewardRuleType, TaskRewardRuleTypeEnum.MATERIAL_TYPE_REWARD.getStatus())
            ) {
                jsonObject = new JsonObject();
            }else{
                jsonObject = JsonParser.parseString(tbKocTask.getRewardSetting()).getAsJsonObject();
            }

            // 审核通过
            switch (TaskRewardRuleTypeEnum.getEnumByType(rewardRuleType)) {
                case FIXED_REWARD:
                    JsonObject fixedRewardSetting = jsonObject.getAsJsonObject("setting");
                    // 固定积分规则
                    int fixedReward = fixedRewardSetting.get("fixedReward").getAsInt();
                    resVo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                    resVo.setTotalPoints(fixedReward);
                    resVo.setProductNum(0);
                    break;
                case INVITATION_REWARD:
                    JsonObject invitationSetting = jsonObject.getAsJsonObject("setting");
                    // 拉新积分规则
                    JsonArray potential = invitationSetting.getAsJsonArray("potential");
                    JsonArray official = invitationSetting.getAsJsonArray("official");
                    int potentialReward = calculateReward(potential, dto.getPotentialNum());
                    // 非潜在用户
                    int officialReward = calculateReward(official, dto.getOfficialNum());
                    // 总分
                    int totalReward = potentialReward + officialReward;
                    resVo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                    resVo.setTotalPoints(totalReward);
                    resVo.setProductNum(0);
                    break;
                case QUALITY_REWARD:
                    //品质积分规则
                    JsonArray qualityRewardSetting = jsonObject.getAsJsonArray("setting");
                    JsonObject rewardByLevel = findRewardByLevel(qualityRewardSetting, dto.getLevel());
                    assert rewardByLevel != null;
                    int baseReward = rewardByLevel.get("baseReward").getAsInt();
                    int productCount = rewardByLevel.get("productCount").getAsInt();
                    if (baseReward > 0 && productCount == 0) {
                        resVo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        resVo.setTotalPoints(baseReward);
                        resVo.setProductNum(0);
                    }
                    if (baseReward == 0 && productCount > 0) {
                        resVo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        resVo.setTotalPoints(0);
                        resVo.setProductNum(productCount);
                    }
                    break;
                case OUT_CHAT_GROUP_REWARD:
                    // 外部群积分规则
                    OutRewardResult outRewardResult = calculateOutReward(jsonObject, dto.getOutGroupChatTimes(), dto.getOutGroupChatNum());
                    if (outRewardResult.getTotalPoints() > 0 && outRewardResult.isGetsProduct()) {
                        resVo.setRewardType(TaskRewardTypeEnum.PRODUCT_POINTS.getStatus());
                        resVo.setTotalPoints(outRewardResult.getTotalPoints());
                        resVo.setProductNum(1);
                    }
                    if (outRewardResult.getTotalPoints() == 0 && outRewardResult.isGetsProduct()) {
                        resVo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        resVo.setTotalPoints(0);
                        resVo.setProductNum(1);
                    }
                    if (outRewardResult.getTotalPoints() > 0 && !outRewardResult.isGetsProduct()) {
                        resVo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        resVo.setTotalPoints(outRewardResult.getTotalPoints());
                        resVo.setProductNum(0);
                    }
                    break;
                case IN_CHAT_GROUP_REWARD:
                case XHS_TYPE_REWARD:
                case MATERIAL_TYPE_REWARD:
                    if (dto.getPoints() > 0 && dto.getProduct() > 0) {
                        // 有产品 有积分
                        resVo.setRewardType(TaskRewardTypeEnum.PRODUCT_POINTS.getStatus());
                        resVo.setTotalPoints(dto.getPoints());
                        resVo.setProductNum(dto.getProduct());
                    }

                    if (dto.getPoints() > 0 && dto.getProduct() == 0) {
                        // 只有积分
                        resVo.setRewardType(TaskRewardTypeEnum.POINTS.getStatus());
                        resVo.setTotalPoints(dto.getPoints());
                        resVo.setProductNum(0);

                    }
                    if (dto.getPoints() == 0 && dto.getProduct() > 0) {
                        // 只有产品
                        resVo.setRewardType(TaskRewardTypeEnum.PRODUCT.getStatus());
                        resVo.setTotalPoints(0);
                        resVo.setProductNum(dto.getProduct());
                    }
                    break;
                default:
                    throw new ServiceException("奖励类型不存在");
            }
            return resVo;
        } else {
            return PreTaskCheckVO.builder().rewardType(null).productNum(0).totalPoints(0).build();
        }

    }


    private void insertPointsLog(TbUserKocTaskInfo tbUserKocTaskInfo, TbUser tbUser, Integer reward) {
        TbUserKocPointsLog tbUserKocPointsLog = new TbUserKocPointsLog();
        tbUserKocPointsLog.setId(IdWorker.getId());
        tbUserKocPointsLog.setType(AdjustUserPointsTypeEnum.PLUSH.getType());
        tbUserKocPointsLog.setKocTaskTypeId(tbUserKocTaskInfo.getKocTaskTypeId());
        tbUserKocPointsLog.setKocTaskId(tbUserKocTaskInfo.getKocTaskId());
        tbUserKocPointsLog.setKocTaskTypeName(tbUserKocTaskInfo.getKocTaskTypeName());
        tbUserKocPointsLog.setKocTaskName(tbUserKocTaskInfo.getKocTaskName());
        tbUserKocPointsLog.setUserId(tbUserKocTaskInfo.getUserId());
        tbUserKocPointsLog.setUserPhone(tbUserKocTaskInfo.getUserPhone());
        tbUserKocPointsLog.setUserRealName(tbUserKocTaskInfo.getUserRealName());
        tbUserKocPointsLog.setUserKocLevelId(tbUser.getKocLevelId());
        tbUserKocPointsLog.setUserPointOld(tbUser.getFreePoints());
        tbUserKocPointsLog.setKocDate(tbUserKocTaskInfo.getKocDate());
        tbUserKocPointsLog.setKocPoint(reward);
        tbUserKocPointsLog.setSourceType(UserPointsSourceTypeEnum.KOC_TASK.getType());
        tbUserKocPointsLog.setSourceId(tbUserKocTaskInfo.getCheckBusinessId().toString());
        tbUserKocPointsLog.setRemarks(AdjustUserPointsTypeEnum.PLUSH.getDesc());
        tbUserKocPointsLog.setCreateTime(new Date());
        tbUserKocPointsLogService.save(tbUserKocPointsLog);
    }


    private void insertProductLog(TbUserKocTaskInfo tbUserKocTaskInfo, TbUser tbUser, Integer productCount) {
        TbUserKocProductLog tbUserKocProductLog = new TbUserKocProductLog();
        long tbUserKocProductLogId = IdWorker.getId();
        tbUserKocProductLog.setId(tbUserKocProductLogId);
        tbUserKocProductLog.setKocTaskTypeId(tbUserKocTaskInfo.getKocTaskTypeId());
        tbUserKocProductLog.setKocTaskId(tbUserKocTaskInfo.getKocTaskId());
        tbUserKocProductLog.setKocTaskTypeName(tbUserKocTaskInfo.getKocTaskTypeName());
        tbUserKocProductLog.setKocTaskName(tbUserKocTaskInfo.getKocTaskName());
        tbUserKocProductLog.setUserId(tbUserKocTaskInfo.getUserId());
        tbUserKocProductLog.setUserPhone(tbUserKocTaskInfo.getUserPhone());
        tbUserKocProductLog.setUserRealName(tbUserKocTaskInfo.getUserRealName());
        tbUserKocProductLog.setUserKocLevelId(tbUser.getKocLevelId());
        tbUserKocProductLog.setKocDate(tbUserKocTaskInfo.getKocDate());
        tbUserKocProductLog.setSourceType(UserProductSourceTypeEnum.KOC_TASK.getType());
        tbUserKocProductLog.setKocProductNum(productCount);
        tbUserKocProductLog.setSourceId(tbUserKocTaskInfo.getCheckBusinessId());
        tbUserKocProductLog.setStatus(0);
        tbUserKocProductLog.setCreateTime(new Date());
        tbUserKocProductLogService.save(tbUserKocProductLog);
        List<TbProductExchangeCoupon> insertData = new ArrayList<>();
        // 插入下发 优惠券
        for (int i = 1; i <= productCount; i++) {
            TbProductExchangeCoupon tbProductExchangeCoupon = new TbProductExchangeCoupon();
            long id = IdWorker.getId();
            tbProductExchangeCoupon.setId(id);
            tbProductExchangeCoupon.setCouponCode(String.valueOf(id));
            tbProductExchangeCoupon.setCouponName(CouponTypeEnum.PHYSICAL.getDesc());
            tbProductExchangeCoupon.setCouponType(CouponTypeEnum.PHYSICAL.getCode());
            tbProductExchangeCoupon.setStatus(CouponStatusEnum.UNUSED.getCode());
            tbProductExchangeCoupon.setUserId(tbUser.getId());
            tbProductExchangeCoupon.setApplicableScope(ApplicableScopeEnum.UNIVERSAL.getCode());
            tbProductExchangeCoupon.setSourceId(tbUserKocProductLogId);
            tbProductExchangeCoupon.setSourceType(CouponSourceTypeEnum.KOC_TASK.getType());
            insertData.add(tbProductExchangeCoupon);
        }
        productExchangeCouponService.saveBatch(insertData);

    }

    /**
     * 计算内部群活跃奖励结果
     */
    public static InRewardResult calculateInReward(JsonObject jsonObject, int actualValue) {
        JsonArray settings = jsonObject.getAsJsonArray("setting");
        int totalPoints = 0;
        int productNum = 0;
        // 遍历所有奖励规则，找到实际值达到的最高阈值
        for (JsonElement element : settings) {
            JsonObject setting = element.getAsJsonObject();
            int threshold = setting.get("threshold").getAsInt();
            // 如果实际值达到或超过该阈值
            if (actualValue >= threshold) {
                int reward = setting.get("reward").getAsInt();
                int product = setting.get("product").getAsInt();
                // 选择最高的阈值对应的奖励
                if (reward > totalPoints || (reward == totalPoints && product > productNum)) {
                    totalPoints = reward;
                    productNum = product;
                }
            }
        }
        return InRewardResult.builder().totalPoints(totalPoints).productNum(productNum).build();
    }


    /**
     * 计算外部群活跃奖励结果
     */
    public static OutRewardResult calculateOutReward(JsonObject jsonObject, int totalChats, int uniqueGroups) {
        JsonObject setting = jsonObject.getAsJsonObject("setting");
        int baseReward = setting.get("baseReward").getAsInt();
        int chatCount = setting.get("chatCount").getAsInt();
        JsonArray steps = setting.getAsJsonArray("steps");
        int totalPoints = calculateTotalPoints(baseReward, steps, totalChats, uniqueGroups);
        boolean getsProduct = totalChats > chatCount;
        return new OutRewardResult(totalPoints, getsProduct);
    }


    public static int calculateTotalPoints(int baseReward, JsonArray steps, int totalChats, int uniqueGroups) {
        // 基础积分 = 总发言次数 × 基础奖励
        int totalPoints = totalChats * baseReward;
        // 计算阶梯额外积分
        int maxExtraReward = 0;
        for (JsonElement element : steps) {
            JsonObject step = element.getAsJsonObject();
            int threshold = Integer.parseInt(step.get("threshold").getAsString());
            int extraReward = Integer.parseInt(step.get("extraReward").getAsString());
            if (uniqueGroups >= threshold && extraReward > maxExtraReward) {
                maxExtraReward = extraReward;
            }
        }
        totalPoints += maxExtraReward;
        return totalPoints;
    }

    public static JsonObject findRewardByLevel(JsonArray settingArray, String targetLevel) {
        for (JsonElement element : settingArray) {
            JsonObject item = element.getAsJsonObject();
            if (item.has("level") && item.get("level").getAsString().equals(targetLevel)) {
                return item;
            }
        }
        return null;
    }

    /**
     * 推人拉新
     */
    public static int calculateReward(JsonArray jsonArray, int actualThreshold) {
        if (actualThreshold <= 0) {
            return 0;
        }
        if (jsonArray == null || jsonArray.size() == 0) {
            return 0;
        }
        // 先尝试查找完全匹配的threshold
        for (JsonElement element : jsonArray) {
            JsonObject obj = element.getAsJsonObject();
            int threshold = obj.get("threshold").getAsInt();

            if (threshold == actualThreshold) {
                return obj.get("reward").getAsInt();
            }
        }
        // 将规则按threshold从小到大排序
        List<JsonObject> sortedRules = new ArrayList<>();
        for (JsonElement element : jsonArray) {
            sortedRules.add(element.getAsJsonObject());
        }
        sortedRules.sort((a, b) -> Integer.compare(a.get("threshold").getAsInt(), b.get("threshold").getAsInt()));

        // 找到第一个大于actualThreshold的规则（下一个更高阈值）
        JsonObject nextHigherRule = null;
        for (JsonObject rule : sortedRules) {
            int threshold = rule.get("threshold").getAsInt();
            if (threshold > actualThreshold) {
                nextHigherRule = rule;
                break;
            }
        }
        if (nextHigherRule != null) {
            // 使用下一个更高阈值的shortfall_multiplier计算
            int baseReward = nextHigherRule.get("reward").getAsInt();
            int shortfallMultiplier = nextHigherRule.get("shortfall_multiplier").getAsInt();
            return (baseReward * shortfallMultiplier) / 100;
        } else {
            // 如果没有找到更高的阈值（说明actualThreshold大于所有阈值），使用最大阈值的奖励
            JsonObject maxRule = sortedRules.get(sortedRules.size() - 1);
            return maxRule.get("reward").getAsInt();
        }
    }

}
